package com.myqf.d4_线程同步.作业;

import lombok.Data;
import lombok.SneakyThrows;

/*
1.春运到了，某个火车站四个售票员出售某个车次最后100张车票的情形。
分析：
火车票： 临界资源
四个售票员：四个线程实例 , 出售车票：卖一张，车票就少一张
 */
public class Test1_4人同时卖票 {
    public static void main(String[] args) {
        Fare fare = new Fare();

        for (int i = 1; i <= 5; i++) {
            new Thread(new Sell(fare),"售票员"+i).start();
        }
    }
}

@Data
class Fare {
    private int ticket = 1000;
    boolean flag = false;

    synchronized void sale() {
        if (ticket > 0) {
            ticket--;
            System.out.println(Thread.currentThread().getName() + "   卖出1张  剩余车票:"+ticket);
        } else {
            flag=true;
            System.out.println("车票卖完了");

        }
    }
}

class Sell implements Runnable{
    static Fare fare;

    Sell(Fare fare) {
        this.fare = fare;
    }

    @SneakyThrows
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"   开始售票");
            while (!fare.flag) {
                    fare.sale();
//                    Thread.yield();// 让票卖的更均匀
            }
    }
}